package com.cloud.wyf.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.cloud.wyf.Entity.*;
import com.cloud.wyf.Entity.Dto.LeaderShipDto;
import com.cloud.wyf.Entity.Dto.MiddelDto;
import com.cloud.wyf.Service.VoteService;
import com.cloud.wyf.Util.GetTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/voting")
public class VoteController {

    private static int currentYear=0;

    @Autowired
    VoteService voteService;

    /**
     * 加载得到当前年份
     */
    static {
        Date date = new Date();
        SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy");
       currentYear = Integer.valueOf(getYearFormat.format(date));
    }

    /**
     * 获取需要投票的中层干部
     * @param request
     * @return
     */
    @RequestMapping("/byOne")
    public String getByOne(HttpServletRequest request){
        //TODO 根据身份插入需要评分的数据表
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        String s=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role");
        int role = Integer.valueOf(s);
        List<Middel> needVote = voteService.getNeedVote(request.getHeader("x-access-token"));
        List<LeaderScore> list=new ArrayList<>();
        List<MiddelScore> list1=new ArrayList<>();
        List<OrdinaryScore> list2=new ArrayList<>();
        if(role==1){
            if(voteService.selectLeaderScoreByUid(uid).size()==0) {
                needVote.stream().forEach(middel -> {
                    LeaderScore leaderScore = new LeaderScore();
                    leaderScore.setLeaderid(uid);
                    leaderScore.setMiddelid(middel.getUid());
                    leaderScore.setYear(currentYear);
                    list.add(leaderScore);
                });
                if (voteService.addLeaderScoreMult(list) <= 0) return JSONObject.toJSONString(Message.failure("atain data failure"));
            }
        }else if(role==3){
            if(voteService.selecOrdinaryScoreByOid(uid).size()==0) {
                needVote.stream().forEach(middel -> {
                    OrdinaryScore ordinaryScore = new OrdinaryScore();
                    ordinaryScore.setOid(uid);
                    ordinaryScore.setMid(middel.getUid());
                    ordinaryScore.setYear(currentYear);
                    list2.add(ordinaryScore);
                });
                if (voteService.addOrdinaryScoreMult(list2) <= 0) return JSONObject.toJSONString(Message.failure("atain data failure"));
            }
        }
        return JSONObject.toJSONString(Message.success(atainDto(needVote, uid, role)));
    }

    /**
     * 获取需要投票的领导班子
     * @param request
     * @return
     */
    @RequestMapping("/ByOnePart")
    public String getByOnePart(HttpServletRequest request){
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        String s=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role");
        int role = Integer.valueOf(s);
        List<LeaderShipScore> list=new ArrayList<>();
        List<LeaderShip> needVote = voteService.getNeedLeaderShip(request.getHeader("x-access-token"));
        if(voteService.selelctLeaderShipScoreByUid(uid).size()==0) {
            needVote.stream().forEach(LeaderShip -> {
                LeaderShipScore leaderShipScore = new LeaderShipScore();
                leaderShipScore.setUid(uid);
                leaderShipScore.setRole(role);
                leaderShipScore.setVotepart(LeaderShip.getPart());
                leaderShipScore.setYear(currentYear);
                list.add(leaderShipScore);
            });
            if (voteService.addLeaderShipScoreMult(list) <= 0) return JSONObject.toJSONString(Message.failure("atain data failure"));
        }
        return JSONObject.toJSONString(Message.success(atainDto1(needVote, uid)));
    }

    /**
     * 投票中层
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/vote")
    public String vote(HttpServletRequest request,HttpServletResponse response){//这里由于前端设置的格式不是json，所以不能用@RequestBody
        int item1 = Integer.valueOf(request.getParameter("item1"));
        int item2=Integer.valueOf(request.getParameter("item2"));
        int item3=Integer.valueOf(request.getParameter("item3"));
        int item4=Integer.valueOf(request.getParameter("item4"));
        int item5=Integer.valueOf(request.getParameter("item5"));
        Float score=Float.valueOf(request.getParameter("score"));
        String detail = request.getParameter("detail");
        String voteid = request.getParameter("voteid");
        if(score<60&&"".equals(detail)) JSONObject.toJSONString(Message.failure("score is lower to 60,have to write reason"));
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        int auth = voteService.isAuth(request.getHeader("x-access-token"));
        int role=Integer.valueOf(GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role"));
        if(auth!=1) return JSONObject.toJSONString(Message.failure("you have no power to vote"));//判断是否可以投
        if(role==1){
            LeaderScore leaderScore=new LeaderScore();
            leaderScore.setLeaderid(uid);
            leaderScore.setMiddelid(voteid);
            leaderScore.setItem1(item1);
            leaderScore.setItem2(item2);
            leaderScore.setItem3(item3);
            leaderScore.setItem4(item4);
            leaderScore.setItem5(item5);
            leaderScore.setScore(score);
            leaderScore.setDescription(detail);
            leaderScore.setYear(currentYear);
            int i = voteService.updateLeaderScore(leaderScore);
            if(i>0) return JSONObject.toJSONString(Message.success("vote is success"));
            else return JSONObject.toJSONString(Message.failure("vote is failure"));
        }else if(role==3){
            OrdinaryScore ordinaryScore=new OrdinaryScore();
            ordinaryScore.setOid(uid);
            ordinaryScore.setMid(voteid);
            ordinaryScore.setItem1(item1);
            ordinaryScore.setItem2(item2);
            ordinaryScore.setItem3(item3);
            ordinaryScore.setItem4(item4);
            ordinaryScore.setItem5(item5);
            ordinaryScore.setScore(score);
            ordinaryScore.setDescription(detail);
            ordinaryScore.setYear(currentYear);
            int i = voteService.updateOrdinaryScore(ordinaryScore);
            if(i>0) return JSONObject.toJSONString(Message.success("vote is success"));
            else return JSONObject.toJSONString(Message.failure("vote is failure"));
        }
        return JSONObject.toJSONString(Message.failure("you need come"));
    }

    /**
     * 投票领导班子
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/votePart")
    public String votePart(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {//这里由于前端设置的格式不是json，所以不能用@RequestBody
        int item1 = Integer.valueOf(request.getParameter("item1"));
        int item2=Integer.valueOf(request.getParameter("item2"));
        int item3=Integer.valueOf(request.getParameter("item3"));
        int item4=Integer.valueOf(request.getParameter("item4"));
        int item5=Integer.valueOf(request.getParameter("item5"));
        Float score=Float.valueOf(request.getParameter("score"));
        String detail = request.getParameter("detail");
        String part = request.getParameter("votepart");
        if(score<60&&"".equals(detail)) JSONObject.toJSONString(Message.failure("score is lower to 60,have to write reason"));
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        int auth = voteService.isAuth(request.getHeader("x-access-token"));
        int role=Integer.valueOf(GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role"));
        if(auth!=1) return JSONObject.toJSONString(Message.failure("you have no power to vote"));//判断是否可以投
            LeaderShipScore leaderScore=new LeaderShipScore();
            leaderScore.setVotepart(part);
            leaderScore.setUid(uid);
            leaderScore.setRole(role);
            leaderScore.setItem1(item1);
            leaderScore.setItem2(item2);
            leaderScore.setItem3(item3);
            leaderScore.setItem4(item4);
            leaderScore.setItem5(item5);
            leaderScore.setScore(score);
            leaderScore.setDescription(detail);
            leaderScore.setYear(currentYear);
            int i = voteService.updateLeaderShipScore(leaderScore);
            if(i>0) return JSONObject.toJSONString(Message.success("vote is success"));
            else return JSONObject.toJSONString(Message.failure("vote is failure"));
    }

    /**
     * 弃权(中层干部投票)
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/quit/{id}")
    public String quit(@PathVariable String id,HttpServletRequest request){
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        int role=Integer.valueOf(GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role"));
        int auth = voteService.isAuth(request.getHeader("x-access-token"));
        if(auth!=1) return JSONObject.toJSONString(Message.failure("you have no power to quit"));//判断是否可以投
       if(role==1) {
           int i = voteService.updateLeaderScoreQuit(uid, id);
           if(i>0) return JSONObject.toJSONString(Message.success("abstain success"));
           else return JSONObject.toJSONString(Message.failure("abstain failure"));
       }else if(role==3){
           int i=voteService.updateOrdinaryScoreQuit(uid,id);
           if(i>0) return JSONObject.toJSONString(Message.success("abstain success"));
           else return JSONObject.toJSONString(Message.failure("abstain failure"));
       }
       else return JSONObject.toJSONString(Message.failure("you have not power"));
    }

    /**
     * 弃权(领导班子投票)
     * @param votepart
     * @param request
     * @return
     */
    @RequestMapping("/quitPart/{votepart}")
    public String quitPart(@PathVariable String votepart,HttpServletRequest request){
        System.out.println(votepart);
        String uid=GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"id");
        int role=Integer.valueOf(GetTokenUtil.getInfoFromToken(request.getHeader("x-access-token"),"role"));
        int auth = voteService.isAuth(request.getHeader("x-access-token"));
        if(auth!=1) return JSONObject.toJSONString(Message.failure("you have no power to quit"));//判断是否可以投
            int i = voteService.updateLeaderShipScoreQuit(uid,votepart);
            if(i>0) return JSONObject.toJSONString(Message.success("abstain success"));
            else return JSONObject.toJSONString(Message.failure("abstain failure"));
    }

    //TODO 需要注意这里是数据初始化，如果不是初始化判断条件可能有待商榷
    public List<MiddelDto> atainDto(List<Middel> list,String currentid,int role){
        List<MiddelDto> list1=new ArrayList<>();
        for(Middel middel:list) {
            if (role == 1) {
                String str="";
               if(voteService.selectByLAndMId(currentid, middel.getUid()).getStatus() != 0) str="已打分";
               else str="未打分";
               if(voteService.selectByLAndMId(currentid, middel.getUid()).getFlag() != 0) str="已弃权";
                if (middel.getStatus()==1) {
                    list1.add(new MiddelDto(middel.getUid(), middel.getRealname(), middel.getPosition(), middel.getLevel(), "已上传", middel.getSummarypath(), middel.getSummarytime(), str, middel.getStatus()));
                } else
                    list1.add(new MiddelDto(middel.getUid(), middel.getRealname(), middel.getPosition(), middel.getLevel(), "未上传", middel.getSummarypath(), middel.getSummarytime(), str, middel.getStatus()));
            }else if(role==3){
                String str="";
                if(voteService.selectByOAndMId(currentid, middel.getUid()).getStatus() != 0) str="已打分";
                else str="未打分";
               if(voteService.selectByOAndMId(currentid, middel.getUid()).getFlag() != 0) str="已弃权";
                if (middel.getStatus()==1) {
                    list1.add(new MiddelDto(middel.getUid(), middel.getRealname(), middel.getPosition(), middel.getLevel(), "已上传", middel.getSummarypath(), middel.getSummarytime(), str, middel.getStatus()));
                } else
                    list1.add(new MiddelDto(middel.getUid(), middel.getRealname(), middel.getPosition(), middel.getLevel(), "未上传", middel.getSummarypath(), middel.getSummarytime(), str, middel.getStatus()));
            }
        }
        return list1;
    }

    public List<LeaderShipDto> atainDto1(List<LeaderShip> list, String currentid){
        List<LeaderShipDto> list1=new ArrayList<>();
        for(LeaderShip middel:list) {
                String str="";
                if(voteService.selectLeaderShipByUAndP(currentid, middel.getPart()).getStatus() != 0) str="已打分";
                else str="未打分";
                if(voteService.selectLeaderShipByUAndP(currentid, middel.getPart()).getFlag() != 0) str="已弃权";
                if (middel.getStatus()==1) {
                    list1.add(new LeaderShipDto(middel.getPart(),"已上传", middel.getReportpath(), middel.getReporttime(),middel.getUid(), str, middel.getStatus()));
                } else
                    list1.add(new LeaderShipDto(middel.getPart(), "未上传", middel.getReportpath(), middel.getReporttime(), middel.getUid(),str, middel.getStatus()));
        }
        return list1;
    }
}
